<template>
    <div ref="earthContainer" class="earth-container"></div>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount} from 'vue'
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

const earthContainer = ref(null);
let scene, camera, renderer, controls, animationFrameId;
const initThreeJS = () => {
    // 创建场景
    scene = new THREE.Scene();
 
    // 创建相机
    camera = new THREE.PerspectiveCamera(75, earthContainer.clientWidth / earthContainer.clientHeight, 0.1, 1000);
    camera.position.z = 5;
 
    // 创建渲染器
    renderer = new THREE.WebGLRenderer();
    renderer.setSize(earthContainer.clientWidth, earthContainer.clientHeight);
    earthContainer.value.appendChild(renderer.domElement);  // 将渲染器挂载到 DOM 容器

    // 添加相机控制--鼠标拖拽旋转
    controls = new OrbitControls(camera, renderer.domElement);

    // 加载地球纹理
    const textureLoader = new THREE.TextureLoader();
    textureLoader.load('https://threejs.org/examples/textures/land_ocean_ice_cloud_2048.jpg', (texture) => {
        const geometry = new THREE.SphereGeometry(1, 32, 32);
        const material = new THREE.MeshBasicMaterial({ map: texture });
        const sphere = new THREE.Mesh(geometry, material);
        scene.add(sphere);
 
        // 动画循环
        const animate = () => {
            requestAnimationFrame(animate);
            sphere.rotation.y += 0.005; // 地球自转效果
            renderer.render(scene, camera);
        };
        animate();
    });
};
// 监听窗口大小变化事件，动态调整相机和渲染器尺寸
const onWindowResize = () => {
    camera.aspect = earthContainer.clientWidth / earthContainer.clientHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(earthContainer.clientWidth, earthContainer.clientHeight);
};
// 初始化 Three.js 场景
onMounted(() => {
    initThreeJS();
    window.addEventListener('resize', onWindowResize);
});
// 清理资源，避免内存泄漏
onBeforeUnmount(() => {
    cancelAnimationFrame(animationFrameId);  // 取消动画循环
    window.removeEventListener('resize', onWindowResize); // 移除事件监听
    renderer.dispose(); // 释放渲染器资源
});
</script>

<style lang="less" scoped>
.earthContainer {
    width: 100%;
    height: 100vh;
    overflow: hidden;
}
</style>